package com.njdf.servlet;

import com.njdf.entity.Page;
import com.njdf.entity.People;
import com.njdf.service.UserService;
import com.njdf.service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
需要单独运行
 */
@WebServlet(name = "demoByPageServlet",urlPatterns = "/demoByPageServlet")
public class demoByPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService=new UserServiceImpl();
        List<People> peoples = userService.queryAll();
        //初始页码
        int startPage=1;
        //页面大小，设置
        int pageSize=3;
        //获取当前页码
        String currentPage1=request.getParameter("currentPage");
        String pageSize1=request.getParameter("SelectOption");
        //先赋值为1
        int currentPage=1;
        if(currentPage1!=null&&pageSize1!=null){
            int currentPage2 = Integer.parseInt(currentPage1);
            int pageSize2=Integer.parseInt(pageSize1);
            currentPage=currentPage2;
            pageSize=pageSize2;
        }
        //总数据数，集合的大小
        int totalCount=peoples.size();
        //总页数
        int totalPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        Page page=new Page(pageSize,totalPage,totalCount,currentPage,startPage);
        List<People> people1=new ArrayList<>();
        for (int i = (currentPage-1)*pageSize; i <currentPage*pageSize ; i++) {
            if(i==peoples.size()){
                break;
            }
            people1.add(peoples.get(i));
        }
        request.setAttribute("page",page);
        request.setAttribute("peoples",people1);
        request.getRequestDispatcher("success1.jsp").forward(request,response);

    }
}
